#include "lgQuantRec.h"
#include "lgCommon.h"

void lgAddQuantOpernRec(stQuantOperRec*  pNewQuantifyRec)
{
    uint8_t  nQuantifyRecIndex = 0;
    int  nQuantifyAddStart = lgGetSetStart( SecQuantifyRec );
    unsigned char nQuantifyRecPos = offsetof( stQuantOperCfg, nRecIndex);
    lgReadBytes( &nQuantifyRecIndex, nQuantifyAddStart + nQuantifyRecPos, 1 );

    nQuantifyRecIndex = nQuantifyRecIndex%QUANT__REC_CNT;
    
    if(nQuantifyRecIndex >= 0 )
    {

        if(pNewQuantifyRec->stopTime >  pNewQuantifyRec->startTime)
        {
           int nLen = pNewQuantifyRec->stopTime - pNewQuantifyRec->startTime;

           SEGGER_RTT_printf( 0, "add new record start %d ---%d = %d\r\n", pNewQuantifyRec->startTime,pNewQuantifyRec->stopTime,nLen);

           lgWriteBytes( SecQuantifyRec, ( uint8_t * )pNewQuantifyRec,
                      nQuantifyAddStart + sizeof( stQuantOperRec )*nQuantifyRecIndex, sizeof( stQuantOperRec ) );
           ++nQuantifyRecIndex;
        
           nQuantifyRecIndex %=  QUANT__REC_CNT;
        
        
           lgWriteBytes( SecQuantifyRec, &nQuantifyRecIndex, nQuantifyAddStart + nQuantifyRecPos, 1 );
        }
        else
        {
           SEGGER_RTT_printf( 0, "quanty record is error \r\n" );
        }
    }
}


void lgUpdateQuantOperRec(stQuantOperRec*  pNewQuantifyRec)
{
    uint8_t  nQuantifyRecIndex = 0;
    int  nQuantifyAddStart = lgGetSetStart( SecQuantifyRec );
    unsigned char nQuantifyRecPos = offsetof( stQuantOperCfg, nRecIndex);
    lgReadBytes( &nQuantifyRecIndex, nQuantifyAddStart + nQuantifyRecPos, 1 );

    nQuantifyRecIndex = nQuantifyRecIndex%QUANT__REC_CNT;
    if(nQuantifyRecIndex >= 0 )
    {

        lgWriteBytes( SecQuantifyRec, ( uint8_t * )pNewQuantifyRec,
                      nQuantifyAddStart + sizeof( stQuantOperRec )*nQuantifyRecIndex, sizeof( stQuantOperRec ) );
    }
}

int  lgGetQuantOperRecIndex()
{
    uint8_t  nQuantifyRecIndex = 0;
    int  nQuantifyAddStart = lgGetSetStart( SecQuantifyRec );
    unsigned char nQuantifyRecPos = offsetof( stQuantOperCfg, nRecIndex);
    lgReadBytes( &nQuantifyRecIndex, nQuantifyAddStart + nQuantifyRecPos, 1 );
    return nQuantifyRecIndex;
}



int lgGetQuantOperRec(uint8_t  nIndex,int nOff,stQuantOperRec*  pQuantOperRec)
{
     int nReadOffSet = 0;
     int nReadPos = ( (nIndex + QUANT__REC_CNT)-1 - nOff) % QUANT__REC_CNT ;
   

     int  nQuantifyAddStart = lgGetSetStart( SecQuantifyRec );
     nReadOffSet =  nQuantifyAddStart + nReadPos*sizeof(stQuantOperRec);

     int nRes =  lgReadBytes((uint8_t *) pQuantOperRec,nReadOffSet, sizeof(stQuantOperRec) );
     
     if( nRes != -1 && (pQuantOperRec->stopTime >  pQuantOperRec->startTime) )
     {
        return 1;
     }
     else
     {
        return 0;
     }
}

void lgQuantOperClear()
{
    int  nQuantifyAddStart = lgGetSetStart( SecQuantifyRec );
    unsigned int nQuantifyAllLen = sizeof(stQuantOperCfg);
    eep_clear_len(SecQuantifyRec, nQuantifyAddStart, nQuantifyAllLen );
}